const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const path = require('path');
// const templating = require('./module/templating');
const controller = require('./controller');
const config = require("./config");
const rest = require("./module/rest");

// const authentication = require('./module/authentication'); 
const apiPrefix = config.apiPrefix;
const isProduction = process.env.NODE_ENV === 'production';
var cors = require('koa-cors');

// record URL
app.use(async (ctx, next) => {
    console.log(ctx.request.method + ' ' + ctx.request.url);
    await next();
});

// static file support:
if (!isProduction) {
    let staticFiles = require('./module/static-files');
    app.use(staticFiles('/static/', __dirname + '/static'));
}

// bodyParser
app.use(bodyParser());

// add nunjucks as view, add ctx.render
// app.use(templating('static/view', {
//     noCache: !isProduction,
//     watch: !isProduction
// }));

app.use(cors());

app.use(rest.restify(apiPrefix));
// Controler & router
app.use(controller(path.resolve(__dirname, './controller')));

app.listen(config.localPort);
console.log('app started at port ' + config.localPort + '...');
